package com.atguigu.gmall.scheduled.job.handler;

import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.omg.CORBA.UnknownUserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spring.web.json.Json;

import javax.jws.Oneway;
import java.util.List;

@Component
public class CartJobHandler {

    private static final String EXCETION_KEY= "exction:cart";

    private static final String KEY_PREFIX = "cart:info:";

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CartMapper cartMapper;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @XxlJob("cartSyncData")
    public ReturnT<String> scheduled(String params){
        //获取redis中的异常数据
        BoundSetOperations<String, String> boundSetOps = redisTemplate.boundSetOps(EXCETION_KEY);
        if (boundSetOps.size()==0){

            return ReturnT.SUCCESS;
        }

        XxlJobLogger.log("sssssssssssssssssssss");
        String userId = boundSetOps.pop();

        while (userId!=null){
            //删除mysql中的购物车数据
            cartMapper.delete(new QueryWrapper<Cart>().eq("user_id",userId));
            //获取redis中的购物车数据
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> values = boundHashOps.values();
            if (CollectionUtils.isEmpty(values)){
                userId = boundSetOps.pop();
                continue;
            }
            String uid = userId;
            values.forEach(item->{
                try {
                    Cart cart = MAPPER.readValue(item.toString(), Cart.class);
                    //添加购物车
                    cart.setUserId(uid);
                    cartMapper.insert(cart);
                } catch (Exception e){
                    e.printStackTrace();

                }
            });
            userId = boundSetOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}
